package cn.quevo.core.file.text;

import cn.quevo.core.exception.CheckParamsException;
import cn.quevo.core.file.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Word解析
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018/08/01 11:46:05
 * @Copyright 东方浩星（北京）传媒科技有限公司版权所有.All Rights Reserved.
 */
public class Word {
    private final static Logger log = LoggerFactory.getLogger(Word.class);

    public static String getContent(File file) {
        if (file == null || !file.exists() || !file.isFile()) {
            throw new CheckParamsException(6021, "文件不存在");
        }
        String fileExt = FileUtils.getFileSuffix(file.getName());
        if (!".doc".equalsIgnoreCase(fileExt) && !".docx".equalsIgnoreCase(fileExt)) {
            throw new CheckParamsException(6020, "文件非Word格式文档");
        }
        try (InputStream inputStream = new FileInputStream(file);) {
            return getContent(inputStream, fileExt);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6022, "文件不存在");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6023, "文件读取失败");
        }
    }

    public static String getContent(InputStream input, String fileExt) {
        String content = "";
        fileExt = FileUtils.getFileSuffix(fileExt);
        // Office 2017之前版本
        if (".doc".equalsIgnoreCase(fileExt)) {
            try (HWPFDocument hdoc = new HWPFDocument(input);) {
                content = hdoc.getRange().text();
                input.close();
                return content;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        // Office 2017及之后版本
        try (XWPFDocument xdoc = new XWPFDocument(input);) {
            content = new XWPFWordExtractor(xdoc).getText();
            input.close();
            xdoc.close();
            return content;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new CheckParamsException(6024, "文件解析失败，文件非Word格式文档");
        }
    }
}
